//
//  CarPriceTVController.m
//  CarStore
//
//  Created by 千锋 on 16/1/26.
//  Copyright (c) 2016年 1000phone. All rights reserved.
//

/** 全国裸车价界面*/
#import "CarPriceTVController.h"
#import "CarPriceListModel.h"
#import "CarPriceListCell.h"


#define API_CAR_PRICE @"http://api.cacaqc.com/car/BrandList"

#define API_CAR_DETAIL @"http://api.cacaqc.com/car/SerialListByBrandId2"
#define API_CAR_BAOMA @"http://api.cacaqc.com/car/SerialListByBrandId2"
@interface CarPriceTVController ()
/** 数据源*/
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation CarPriceTVController
/** 懒加载*/
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//     Uncomment the following line to preserve selection between presentations.
     self.clearsSelectionOnViewWillAppear = NO;

    self.tableView.rowHeight = 60;
    
    // 数据请求
    [self requestData];
    
    // 注册表格
    [self.tableView registerNib:[UINib nibWithNibName:@"CarPriceListCell" bundle:nil] forCellReuseIdentifier:@"CarPriceListCellID"];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 数据相关
/** 创建下拉刷新控件*/
- (void)requestData
{
    [MBProgressHUD showMessage:@"正在加载..."];
    [AFHTTPSessionManager POST:API_CAR_PRICE parmaeters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSMutableArray *bodys = responseObject[@"body"];
        NSMutableArray *spells = @[].mutableCopy;
        // 取出字母
        for (NSDictionary *dic in bodys) {
            if (![spells containsObject:dic[@"spell"]]&&![dic[@"spell"] isEqualToString:@""]) {
                [spells addObject:dic[@"spell"]];
            }
        }
        // 给字母排序
        NSArray *newSpells = [spells sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
            return [obj1 compare:obj2];
        }];
        
        for (NSString *spell in newSpells) {
            NSMutableArray *modelArr = @[].mutableCopy;
            NSMutableDictionary *dict = @{}.mutableCopy;
            for (NSDictionary *dic in bodys) {
                if ([spell isEqualToString:dic[@"spell"]]) {
                    CarPriceListModel *model = [CarPriceListModel modelWithDic:dic];
                    [modelArr addObject:model];
                }
            }
            [dict setValue:modelArr forKey:@"model"];
            [dict setValue:spell forKey:@"spell"];
            [self.dataArray addObject:dict];
        }
        [self showSuccess:YES status:@"加载成功"];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self showSuccess:NO status:@"加载失败"];
    }];
}
// 停止隐藏并提示是否加载成功
- (void)showSuccess:(BOOL)isSucc status:(NSString *)status
{
    [MBProgressHUD hideHUD];
    if (isSucc) {
        [SVProgressHUD showSuccessWithStatus:status];
        [self.tableView reloadData];
    }else{
        [SVProgressHUD showErrorWithStatus:status];
    }
}

#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = [self.dataArray[section] objectForKey:@"model"];
    return arr.count;
}
// 创建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CarPriceListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CarPriceListCellID"];
   
    NSArray *models = [self.dataArray[indexPath.section] objectForKey:@"model"];
    CarPriceListModel *model = models[indexPath.row];
    cell.titleLabel.text = model.name;
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:model.icon] placeholderImage:[UIImage imageNamed:@"placeholder_image"]];
    cell.priceLabel.text = @"90";
    return cell;
}
// 返回组头的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self.dataArray[section] objectForKey:@"spell"];
}

// 返回组的索引标题
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *arr = @[].mutableCopy;
    for (NSDictionary *dic in self.dataArray) {
        [arr addObject:dic[@"spell"]];
    }
    return arr;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    NoDataViewController *noDataVC = [sb instantiateViewControllerWithIdentifier:@"NoDataViewController"];
    [self push:^{
        [self.navigationController pushViewController:noDataVC animated:YES];
    }];
}
// 隐藏控制栏
- (void)push:(void(^)(void))push
{
    self.hidesBottomBarWhenPushed = YES;
    push();
    self.hidesBottomBarWhenPushed = NO;
}
@end
